package com.cg.asm.core.util;

import com.alibaba.fastjson.JSONObject;
import com.cg.asm.license.encryption.AESUtil;
import com.cg.asm.license.holder.LicenseVerifyHolder;
import com.cg.asm.license.verify.LicenseVerify;
import com.cg.asm.core.config.loading.StartupLoading;
import com.cg.asm.core.domain.vo.menu.MenuPointsVO;
import com.cg.asm.core.domain.vo.user.UserLoginVO;
import com.cg.asm.client.CommonUtil;
import com.cg.asm.client.constans.ConstantsEnum;
import com.cg.asm.client.exception.AsmException;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;

import java.io.PrintWriter;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AsmApiUtils {

    public static UserLoginVO getCurrentUserLoginVO() {
        UserLoginVO userLoginVO;
        try {
            Object principalObj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (null != principalObj && !"anonymousUser".equals(principalObj.toString())) {
                userLoginVO = (UserLoginVO) principalObj;
            } else {
                userLoginVO = null;
            }
        } catch (NullPointerException e) {
            userLoginVO = null;
        }
        return userLoginVO;
    }

    public static UserLoginVO getCurrentUserLoginVO(SessionRegistry sessionRegistry, String token) {
        UserLoginVO userLoginVO;
        SessionInformation sessionInformation = sessionRegistry.getSessionInformation(token);
        if (null != sessionInformation) {
            userLoginVO = (UserLoginVO) sessionInformation.getPrincipal();
        } else {
            userLoginVO = new UserLoginVO();
        }
        return userLoginVO;
    }

    public static JSONObject getCurrentUserInfo(SessionRegistry sessionRegistry, String token) {
        UserLoginVO userLoginVO = AsmApiUtils.getCurrentUserLoginVO(sessionRegistry, token);
        if (StringUtil.isNotEmpty(userLoginVO.getUsername())) {
            return AsmCommonUtil.successUserInfo(userLoginVO);
        } else {
            String returnCode = ConstantsEnum.RESPONSE_E_BAAA.getKey();
            String returnMsg = ConstantsEnum.RESPONSE_E_BAAA.getValue();
            return CommonUtil.errorJson(returnCode, returnMsg);
        }
    }

    /**
     * 功能点授权查询
     *
     * @param userPoints
     * @param permissionValue
     * @return
     */
    public static boolean permission(List<MenuPointsVO> userPoints, String permissionValue) {
        boolean permissionResult = false;
        if (StringUtils.isNotEmpty(permissionValue)) {
            for (MenuPointsVO mo : userPoints) {
                if (permissionValue.equals(mo.getFunPointsCode())) {
                    permissionResult = true;
                    break;
                }
            }
        }
        return permissionResult;
    }

    /**
     * token加工处理
     *
     * @param sessionId
     * @return
     */
    public static String tokenHandle(String sessionId) {
        LicenseVerify lv = LicenseVerifyHolder.getLicenseVerify(StartupLoading.licenseInputStream);
        String resultValue = lv.verify();
        if (!"success".equals(resultValue)) {
            throw new AsmException(resultValue);
        } else {
            if (StringUtils.isNotEmpty(sessionId)) {
                String key = lv.getEncryptionKey();
                return AESUtil.getInstance().encrypt(sessionId, key);
            } else {
                throw new AsmException("tokenHandle缺失重要参数");
            }
        }
    }

    /**
     * token加工处理
     *
     * @param token
     * @return
     */
    public static String tokenDecrypt(String token) {
        LicenseVerify lv = LicenseVerifyHolder.getLicenseVerify(StartupLoading.licenseInputStream);
        String resultValue = lv.verify();
        if (!"success".equals(resultValue)) {
            throw new AsmException(resultValue);
        } else {
            if (StringUtil.isNotEmpty(token)) {
                String key = lv.getEncryptionKey();
                return AESUtil.getInstance().decrypt(token, key);
            } else {
                return "";
            }
        }
    }

    /**
     * 去除字符串中的空格、回车、换行符、制表符
     *
     * @param str
     * @return
     */
    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    public static void outPrintlnByJSONObject(PrintWriter out, JSONObject jSONObject) {
        try {
            out.println(jSONObject);
        } finally {
            if (null != out) {
                out.flush();
                out.close();
            }
        }
    }
}
